package com.mindcraft.shop.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mindcraft.base.utils.CommonConst;
import com.mindcraft.base.utils.RedisConst;
import com.mindcraft.shop.client.UserClient;
import com.mindcraft.shop.mapper.SkuDetailMapper;
import com.mindcraft.shop.mapper.SkuImageMapper;
import com.mindcraft.shop.mapper.SkuMapper;
import com.mindcraft.shop.po.CommunityComment;
import com.mindcraft.shop.po.SkuDetail;
import com.mindcraft.shop.po.SkuImage;
import com.mindcraft.shop.po.SkuInfo;
import com.mindcraft.shop.service.SkuInfoService;

import com.mindcraft.shop.vo.CommonSkuVo;
import com.mindcraft.shop.vo.SkuInfoQueryVo;
import com.mindcraft.user.po.McUser;
import com.mindcraft.user.vo.UserLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author Mr.M
 * @version 1.0
 * @description 微信扫码认证
 * @date 2022/9/29 12:12
 */
@Slf4j
@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, SkuInfo> implements SkuInfoService {

    @Autowired
    private SkuDetailMapper skuDetailMapper;

    @Autowired
    private UserClient userClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public IPage<SkuInfo> selectPageSkuInfo(Page<SkuInfo> pageParam, SkuInfoQueryVo skuInfoVo) {

        String keyword = skuInfoVo.getKeyword();
        Long categoryId = skuInfoVo.getCategoryId();
        String skuType = skuInfoVo.getSkuType();
        LambdaQueryWrapper<SkuInfo> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(keyword)) {
            wrapper.like(SkuInfo::getSkuName, keyword);
        }
        if (!StringUtils.isEmpty(categoryId)) {
            wrapper.eq(SkuInfo::getCategoryId, categoryId);
        }
        if (!StringUtils.isEmpty(skuType)) {
            wrapper.like(SkuInfo::getSkuType, skuType);
        }
        IPage<SkuInfo> pageModel = baseMapper.selectPage(pageParam, wrapper);

        pageModel.getRecords().stream().forEach(skuInfo -> {
            //TODO 放入缓存
            LambdaQueryWrapper<SkuDetail> skuDetailWrapper = new LambdaQueryWrapper<>();
            skuDetailWrapper.eq(SkuDetail::getSkuId, skuInfo.getId());
            SkuDetail skuDetail = skuDetailMapper.selectOne(skuDetailWrapper);


            skuInfo.setIsNew(skuDetail.getIsNew());
            skuInfo.setIsFreepost(skuDetail.getIsFreepost());
            skuInfo.setBeforePrice(skuDetail.getBeforePrice());
            skuInfo.setPostAddress(skuDetail.getPostAddress());

            skuInfo.setUserId(skuDetail.getUserId());


            //通过远程调用查询用户信息
            if (redisTemplate.hasKey(CommonConst.USER_ACCESS_TOKEN + skuDetail.getUserId())) {
                UserLoginVo userLoginVo = (UserLoginVo) redisTemplate.opsForValue().get(CommonConst.USER_ACCESS_TOKEN + skuDetail.getUserId());
                skuInfo.setNickName(userLoginVo.getNickName());
                skuInfo.setPhotoUrl(userLoginVo.getPhotoUrl());
                skuInfo.setUserId(userLoginVo.getUserId());
            } else {
                McUser user = userClient.getUser(skuInfo.getUserId());
                UserLoginVo userLoginVo = new UserLoginVo();
                userLoginVo.setPhotoUrl(user.getUserpic());
                userLoginVo.setUserId(user.getId());
                userLoginVo.setNickName(user.getUsername());
                userLoginVo.setOpenId(user.getOpenId());

                redisTemplate.opsForValue().set(CommonConst.USER_ACCESS_TOKEN + skuDetail.getUserId(), userLoginVo, CommonConst.TOKEN_EXPIRE, TimeUnit.SECONDS);
            }


        });


        return pageModel;


    }

    @Autowired
    private SkuImageMapper skuImageMapper;

    @Override
    public CommonSkuVo getCommonSku(CommonSkuVo commonSkuVo) {

        //触底前端只传入分类id,,不需要查询用户点击的skuid
        if (commonSkuVo.getSkuId() == null) {
            //触底逻辑,,只分页
            //通过分类id查询出相同的sku
            lambdaQuery().eq(SkuInfo::getCategoryId, commonSkuVo.getCategoryId())
                    .orderByDesc(SkuInfo::getCreateTime)
                    .page(commonSkuVo);
            List<SkuInfo> records = commonSkuVo.getRecords();
            records.stream().forEach((skuInfo) -> {


                //为sku添加商品图片
                List<SkuImage> skuImageList = skuImageMapper.selectList(new LambdaQueryWrapper<SkuImage>()
                        .eq(SkuImage::getSkuId, skuInfo.getId()));

                if (!CollectionUtils.isEmpty(skuImageList)) {
                    skuImageList.stream().forEach((img) -> {
                        List<String> skuImgList = skuInfo.getSkuImgList();
                        if (skuImgList == null) {
                            skuImgList = new ArrayList<>();
                        }
                        skuImgList.add(img.getImgUrl());
                        skuInfo.setSkuImgList(skuImgList);
                    });

                }

                //添加商品详情
                SkuDetail skuDetail = skuDetailMapper.selectOne(
                        new LambdaQueryWrapper<SkuDetail>().eq(SkuDetail::getSkuId, skuInfo.getId()));

                skuInfo.setUserId(skuDetail.getUserId());

                skuInfo.setIsNew(skuDetail.getIsNew());
                skuInfo.setIsFreepost(skuDetail.getIsFreepost());
                skuInfo.setBeforePrice(skuDetail.getBeforePrice());
                skuInfo.setPostAddress(skuDetail.getPostAddress());



                //通过远程调用查询用户信息
                if (redisTemplate.hasKey(CommonConst.USER_ACCESS_TOKEN + skuDetail.getUserId())) {
                    UserLoginVo userLoginVo = (UserLoginVo) redisTemplate.opsForValue().get(CommonConst.USER_ACCESS_TOKEN + skuDetail.getUserId());
                    skuInfo.setNickName(userLoginVo.getNickName());
                    skuInfo.setPhotoUrl(userLoginVo.getPhotoUrl());
                    skuInfo.setUserId(userLoginVo.getUserId());
                } else {
                    McUser user = userClient.getUser(skuInfo.getUserId());
                    UserLoginVo userLoginVo = new UserLoginVo();
                    userLoginVo.setPhotoUrl(user.getUserpic());
                    userLoginVo.setUserId(user.getId());
                    userLoginVo.setNickName(user.getUsername());
                    userLoginVo.setOpenId(user.getOpenId());

                    redisTemplate.opsForValue().set(CommonConst.USER_ACCESS_TOKEN + skuDetail.getUserId(), userLoginVo, CommonConst.TOKEN_EXPIRE, TimeUnit.SECONDS);
                }

            });
            return commonSkuVo;

        } else {
            //非触底逻辑,用户第一次点击传入skuid
            //设置用户点击的sku信息
            SkuInfo click_skuInfo = baseMapper.selectById(commonSkuVo.getSkuId());


            SkuDetail skuDetail1 = skuDetailMapper.selectOne(new LambdaQueryWrapper<SkuDetail>().eq(SkuDetail::getSkuId, commonSkuVo.getSkuId()));
            click_skuInfo.setUserId(skuDetail1.getUserId());


            click_skuInfo.setIsNew(skuDetail1.getIsNew());
            click_skuInfo.setIsFreepost(skuDetail1.getIsFreepost());
            click_skuInfo.setBeforePrice(skuDetail1.getBeforePrice());
            click_skuInfo.setPostAddress(skuDetail1.getPostAddress());

            //为点击的sku添加商品图
            List<SkuImage> click_skuImageList = skuImageMapper.selectList(new LambdaQueryWrapper<SkuImage>()
                    .eq(SkuImage::getSkuId, click_skuInfo.getId()));

            if (!CollectionUtils.isEmpty(click_skuImageList)) {
                click_skuImageList.stream().forEach((img) -> {
                    List<String> skuImgList = click_skuInfo.getSkuImgList();
                    if (skuImgList == null) {
                        skuImgList = new ArrayList<>();
                    }
                    skuImgList.add(img.getImgUrl());
                    click_skuInfo.setSkuImgList(skuImgList);
                });

            }

            //通过远程调用查询用户信息
            if (redisTemplate.hasKey(CommonConst.USER_ACCESS_TOKEN + skuDetail1.getUserId())) {
                UserLoginVo userLoginVo = (UserLoginVo) redisTemplate.opsForValue().get(CommonConst.USER_ACCESS_TOKEN + skuDetail1.getUserId());
                click_skuInfo.setNickName(userLoginVo.getNickName());
                click_skuInfo.setPhotoUrl(userLoginVo.getPhotoUrl());
                click_skuInfo.setUserId(userLoginVo.getUserId());

            } else {
                McUser user = userClient.getUser(click_skuInfo.getUserId());
                UserLoginVo userLoginVo = new UserLoginVo();
                userLoginVo.setPhotoUrl(user.getUserpic());
                userLoginVo.setUserId(user.getId());
                userLoginVo.setNickName(user.getUsername());
                userLoginVo.setOpenId(user.getOpenId());
            }


            commonSkuVo.setSkuInfo(click_skuInfo);
            //通过分类id查询出相同的sku
            lambdaQuery().eq(SkuInfo::getCategoryId, click_skuInfo.getCategoryId())
                    .orderByDesc(SkuInfo::getCreateTime)
                    .page(commonSkuVo);

            List<SkuInfo> records = commonSkuVo.getRecords();
            records.stream().forEach((skuInfo) -> {
                SkuDetail skuDetail = skuDetailMapper.selectOne(
                        new LambdaQueryWrapper<SkuDetail>()
                                .eq(SkuDetail::getSkuId, skuInfo.getId()));

                skuInfo.setIsNew(skuDetail.getIsNew());
                skuInfo.setIsFreepost(skuDetail.getIsFreepost());
                skuInfo.setBeforePrice(skuDetail.getBeforePrice());
                skuInfo.setPostAddress(skuDetail.getPostAddress());

                //为sku添加商品图片
                List<SkuImage> skuImageList = skuImageMapper.selectList(new LambdaQueryWrapper<SkuImage>()
                        .eq(SkuImage::getSkuId, skuInfo.getId()));

                if (!CollectionUtils.isEmpty(skuImageList)) {
                    skuImageList.stream().forEach((img) -> {
                        List<String> skuImgList = skuInfo.getSkuImgList();
                        if (skuImgList == null) {
                            skuImgList = new ArrayList<>();
                        }
                        skuImgList.add(img.getImgUrl());
                        skuInfo.setSkuImgList(skuImgList);
                    });

                }


                skuInfo.setUserId(skuDetail.getUserId());

                //通过远程调用查询用户信息
                if (redisTemplate.hasKey(CommonConst.USER_ACCESS_TOKEN + skuDetail.getUserId())) {
                    UserLoginVo userLoginVo = (UserLoginVo) redisTemplate.opsForValue().get(CommonConst.USER_ACCESS_TOKEN + skuDetail.getUserId());
                    skuInfo.setNickName(userLoginVo.getNickName());
                    skuInfo.setPhotoUrl(userLoginVo.getPhotoUrl());
                    skuInfo.setUserId(userLoginVo.getUserId());
                } else {
                    McUser user = userClient.getUser(skuInfo.getUserId());
                    UserLoginVo userLoginVo = new UserLoginVo();
                    userLoginVo.setPhotoUrl(user.getUserpic());
                    userLoginVo.setUserId(user.getId());
                    userLoginVo.setNickName(user.getUsername());
                    userLoginVo.setOpenId(user.getOpenId());
                }
            });


            return commonSkuVo;
        }


    }

}